<template>
  <div v-if="resetRouterView" class="app-content-main">
    <router-view v-slot="{ Component, route }">
      <keep-alive :include="cachedRoutes" :max="keepAliveMaxNum">
        <component :is="Component" :key="route.path" />
      </keep-alive>
    </router-view>
  </div>
</template>

<script setup>
import { reactive, toRefs, getCurrentInstance, nextTick, onMounted, computed } from 'vue'
import { Setting } from '@/config'
import { useTabviewStore } from '@/store/modules/tabview'

// 获取全局属性
const { proxy } = getCurrentInstance()
const state = reactive({
  keepAliveMaxNum: Setting.keepAliveMaxNum,
  resetRouterView: true
})
const { keepAliveMaxNum, resetRouterView } = toRefs(state)

// store
const tabviewStore = useTabviewStore()
// 路由数据
const visitedRoutes = computed(() => tabviewStore.visitedRoutes)

// 路由name与page.name匹配
const cachedRoutes = computed(() => {
  let cachedRoutesArr = []

  visitedRoutes.value.forEach((item) => {
    if (!item.meta.noKeepAlive) {
      item.name && cachedRoutesArr.push(item.name)
    }
  })
  return cachedRoutesArr
})

onMounted(() => {
  //重载所有路由
  proxy.$eventBus.on('reload-router-view', () => {
    state.resetRouterView = false
    nextTick(() => {
      state.resetRouterView = true
    })
  })
})
</script>
